<template>
  <div class="python-batch-testing">
    <a-form :form="form">
      <a-form-item label="模型编号" :labelCol="{ span: 4 }" :wrapperCol="{ span: 12 }">
        <a-input disabled v-decorator="['modelUuid']" />
      </a-form-item>
      <a-form-item label="模型名称" :labelCol="{ span: 4 }" :wrapperCol="{ span: 12 }">
        <a-input disabled v-decorator="['name']" />
      </a-form-item>
      <a-form-item label="模型版本" :labelCol="{ span: 4 }" :wrapperCol="{ span: 12 }">
        <a-input disabled v-decorator="['version']" />
      </a-form-item>
      <a-form-item label="测试文件" :labelCol="{ span: 4 }" :wrapperCol="{ span: 12 }">
        <a-space class="upload-space">
          <a-tooltip title="文件大小在 100M 以内,第一行为表头,仅支持csv格式。">
            <a-upload
              v-decorator="['testFile', { rules: [{ required: true, message: '请上传模型文件' }] }]"
              name="file"
              :multiple="false"
              :before-upload="beforeUpload"
            >
              <a-button><a-icon type="upload" /> 选择文件</a-button>
            </a-upload>
          </a-tooltip>
          <a-button @click="handleDownload"><a-icon type="download" /> 测试文件模板下载</a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <a-button type="primary" block @click="handleTest" :loading="loading"> {{ buttonText }} </a-button>
    <a-drawer
      title="结果信息"
      :visible.sync="visible"
      width="30%"
      @close="visible = false"
      :getContainer="$drawerConfig.getContainer"
    >
      <a-steps direction="vertical" size="small" :current="2">
        <a-step title="上传文件成功" />
        <a-step :title="message" />
        <a-step title="执行CSV文件测试Model成功" />
      </a-steps>
      <a-descriptions :column="1" bordered>
        <a-descriptions-item label="总共条数">
          {{ resultData.total_line }}
        </a-descriptions-item>
        <a-descriptions-item label="成功条数">
          {{ resultData.success_line }}
        </a-descriptions-item>
        <a-descriptions-item label="失败条数">
          {{ resultData.error_line }}
        </a-descriptions-item>
      </a-descriptions>
      <a-button
        type="primary"
        @click="handleResult"
        block
        class="result-btn"
        icon="import"
        style="margin-top: 20px">
        查看测试结果
      </a-button>
    </a-drawer>
  </div>
</template>

<script>
import { modelTestTempDownLoad, pythonModelUploadTestFile, pythonModelUploadTestResult } from '@/api/manage'

export default {
  name: 'PythonBatchTesting',
  props: {
    currentDetailRecord: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      form: this.$form.createForm(this),
      visible: false,
      message: '',
      resultData: {},
      loading: false,
      buttonText: '点击测试',
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    initData() {
      this.$nextTick(() => {
        const { uuid, name, version } = this.currentDetailRecord
        console.log(uuid, name, version)
        this.form.setFieldsValue({
          modelUuid: uuid,
          name,
          version,
        })
      })
    },
    beforeUpload(file) {
      // 根据文件类型进行不同的验证
      const isCSV = file.name.toLowerCase().endsWith('.csv')
      if (!isCSV) {
        this.$message.error('模板文件只支持 .csv 格式的文件')
        return false
      }

      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isLt100M) {
        this.$message.error('文件大小不能超过100MB')
        return false
      }

      // 返回 false 阻止自动上传
      return false
    },
    handleDownload() {
      const { uuid, version } = this.currentDetailRecord
      modelTestTempDownLoad(
        { modelUuid: uuid, version },
        {
          defaultFileName: 'test_data_temp.csv',
        }
      )
    },
    handleTest() {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        this.loading = true
        this.buttonText = '测试中请稍等...'
        const params = {
          modelUuid: values.modelUuid,
          version: values.version,
          testFile: values.testFile.file,
        }
        const formData = new FormData()
        Object.keys(params).forEach((key) => {
          formData.append(key, params[key])
        })
        pythonModelUploadTestFile(formData).then((res) => {
          if (res.code === 200) {
            this.message = res.message
            pythonModelUploadTestResult({
              ip: res.data,
              version: values.version,
              modelUuid: values.modelUuid,
            })
              .then((result) => {
                console.log(result)
                if (result.code === 200) {
                  this.resultData = result.data
                  this.visible = true
                  this.loading = false
                  this.$message.success('测试成功')
                  this.buttonText = '点击测试'
                } else {
                  // 失败则循环调用间隔1s调用一次
                  setTimeout(() => {
                    this.handleTest()
                  }, 1000)
                }
              })
              .catch(() => {
                this.loading = false
                this.buttonText = '点击测试'
              })
          }
        })
      })
    },
    handleResult() {
      this.$router.push({
        path: '/model/modelLog',
        query: {
          currentTab: '3',
        },
      })
    },
  },
}
</script>
<style lang="less" scoped>
.upload-space {
  align-items: flex-start;
}
</style>
